package com.jy.appmarket.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

public class LogUtil {
	private static final boolean DEBUG = Log.isLoggable("AppMarket", Log.DEBUG);
	private static boolean sFileLog = false;
	private static String sFileName;

	public static void setFileLogEnable(Context context, boolean enable) {
		if (!enable) {
			sFileLog = false;
			return;
		}
		if (context == null) {
			Log.d("LogUtil", "context is null");
			return;
		}
		sFileLog = true;
		sFileName = context.getPackageName() + ".log";
		return;
	}

	public static void i(String tag, String msg) {
		if (DEBUG) {
			Log.i(tag, msg);
			if (sFileLog) {
				writeFile("I", tag, msg);
			}
		}
	}

	public static void e(String tag, String msg, Throwable t) {
		e(tag, msg + '\n' + Log.getStackTraceString(t));
	}

	public static void e(String tag, String msg) {
		if (DEBUG) {
			Log.e(tag, msg);
			if (sFileLog) {
				writeFile("E", tag, msg);
			}
		}
	}

	public static void d(String tag, String msg) {
		if (DEBUG) {
			Log.d(tag, msg);
			if (sFileLog) {
				writeFile("D", tag, msg);
			}
		}
	}

	public static void w(String tag, String msg, Throwable t) {
		w(tag, msg + '\n' + Log.getStackTraceString(t));
	}

	public static void w(String tag, String msg) {
		if (DEBUG) {
			Log.w(tag, msg);
			if (sFileLog) {
				writeFile("W", tag, msg);
			}
		}
	}

	public static void v(String tag, String msg) {
		if (DEBUG) {
			Log.v(tag, msg);
			if (sFileLog) {
				writeFile("V", tag, msg);
			}
		}
	}

	private static Handler sHandler;
	private static SimpleDateFormat sFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

	private static void writeFile(final String level, final String tag, final String log) {
		if (sHandler == null) {
			HandlerThread ht = new HandlerThread("log");
			ht.start();
			sHandler = new Handler(ht.getLooper());
		}
		sHandler.post(new Runnable() {
			@Override
			public void run() {
				File file = new File(Environment.getExternalStorageDirectory(), sFileName);
				if (!file.exists()) {
					return;
				}
				if (file.length() > 1024 * 1024 * 5) {// 5M
					Log.d("Log", "log file too large");
					return;
				}
				try {
					FileWriter writer = new FileWriter(file, true);
					String content = String.format("%s %-4s%-20s%s\r\n", sFormatter.format(new Date()), level, tag,
							log);
					writer.write(content);
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}
}
